package com.lashou.labeutil.util;

import java.io.FileReader;
import java.io.FileWriter;

import java.io.RandomAccessFile;
import java.io.Serializable;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;


/**
 * 文件操作工具类
 * @author fengbo
 *@modify by wangzh date:2010-4-13 content:add synchronized for method
 */
public class FileUtil implements Serializable {

	private static final long serialVersionUID = 1L;

	/**
	 * 创建文件
	 * @author fengbo
	 * @param filePath
	 * @return
	 */
	public static synchronized java.io.File createFile(String filePath){
		try{
			java.io.File f = new java.io.File(filePath);
			if(!f.exists()){
				f.createNewFile();
			}
			return f;
		}catch(Exception e){
			return null;
		}
	}
	/**
	 * 创建目录
	 * @param filePath
	 * @return
	 */
	public static synchronized boolean createMkdir(String mkdirPath){
		try{
			java.io.File f = new java.io.File(mkdirPath);
			if(!f.exists()){
				return f.mkdirs();
			}
			return true;
		}catch(Exception e){
			return false;
		}
	}
	/**
	 * 删除文件
	 * @author fengbo
	 * @param filePath
	 * @return
	 */
	public static synchronized int delFile(String filePath){
		try{
			java.io.File f = new java.io.File(filePath);
			if(f.exists()){
				f.delete();
				return 1;
			}else{
				return 1;
			}
		}catch(Exception e){
			return 0;
		}
	}
	/**
	 * 获得文件中的内容
	 * @param filePath
	 * @return
	 */
	public static String  readFile(java.io.File file){
		StringBuffer sb = new StringBuffer();
		String str = "";
		try {
		FileReader fr = new java.io.FileReader(file);
			java.io.BufferedReader red = new java.io.BufferedReader(fr);
			while((str = red.readLine())!=null){
				sb.append(str+"\n");
			}
			red.close();
			fr.close();
		
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return sb.toString();
	}
	/**
	 * 写入文件
	 * @param file
	 * @param writeStr
	 * @return
	 * @modify by wangzc . date:2010-4-13 add return values;
	 */
	public static synchronized int writeFile(java.io.File file,String writeStr){
		try {
			java.io.FileOutputStream outStream = new java.io.FileOutputStream(file);
			outStream.write(writeStr.getBytes());
			outStream.flush();
			outStream.close();
			return 1;
		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		}
		
	}
	/**
	 * 以追加方式写入文件
	 * @param file
	 * @param writeStr
	 * @return
	 */
	public static synchronized int writeFileAdd(java.io.File file,String writeStr){
		try {
			 FileWriter fw = new  FileWriter(file,true);
			 fw.write(writeStr);
			 fw.flush();
			 fw.close();
			//java.io.FileOutputStream outStream = new java.io.FileOutputStream(file);
			//outStream.write(writeStr.getBytes());
		} catch (Exception e) {
		
			e.printStackTrace();
		}
		return 0;
	}
	/**
	 * 给文件加锁
	 * @author fengbo
	 * @param file
	 * @return
	 */
	public static FileLock lockFie(java.io.File file){
		try {
		 RandomAccessFile raf = new RandomAccessFile(file, "rw"); //r ,rw ,rwd 三个可选参数
		 FileChannel fc = raf.getChannel();
		 FileLock fl = fc.tryLock();
		 return fl;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

	}
	/**
	 * 释放文件锁
	 * @param fl
	 */
	public static void freeLock(FileLock fl){
		try{
			if(null!=fl){
				fl.release();
			}
		}catch(Exception e){
			
		}
	}
	/**
	 * 文件上传
	 * @param request
	 * @param response
	 * @return
	 *//*
	public static boolean uploadfile(FormFile myFile,String filepath){
		if(myFile==null){System.out.println("上传文件为空。。。");return false;}
		try{
			 FileUtil.createFile(filepath+myFile.getFileName());
			 FileOutputStream fos = new FileOutputStream(filepath+myFile.getFileName());
			 fos.write(myFile.getFileData());
			 fos.flush();
			 fos.close();
		}catch(Exception e){
			return false;
		}
		return true;
	}*/
	/**
	 * 文件下载 
	 * @param request
	 * @param response
	 * @param path 文件绝对路径   /tmp/tool.exe
	 * @return
	 *//*
	public static boolean downloadFile(HttpServletRequest request,HttpServletResponse response,String path){
		String filename = "";
		String fileminitype = "text/plain";
	try {
			java.io.File f = new java.io.File(path);
			if(f==null){System.out.println("file 为空");return false;}
			filename =f.getName();
			System.out.println("filename ============="+filename);
			response.setContentType(fileminitype);
			response.setHeader("Location", filename);
			response.setHeader("Content-Disposition", "attachment; filename="+ filename);
			OutputStream outputStream = response.getOutputStream();
			InputStream inputStream = new FileInputStream(f);
			byte[] buffer = new byte[1024];
			int i = -1;
			while ((i = inputStream.read(buffer)) != -1) {
				outputStream.write(buffer, 0, i);
			}
			outputStream.flush();
			outputStream.close();
			inputStream.close();
			outputStream = null;
			return true;
		} catch (Exception e) {
			return false;
		}

	}*/
	/**
	 * 判断文件是否存在
	 * @param filePath
	 * @return
	 */
	public static boolean checkFileEx(String filePath){
		try{
		java.io.File f = new java.io.File(filePath);
			return f.exists();
		}catch(Exception e){
			return false;
		}
	
	}
	/**
	 * 更新文件 参数均不能为空
	 * 
	 * @param file
	 *            文件
	 * @param key
	 *            文件中的key 形如 key=value
	 * @param newStr
	 *            将key=value中的“value” 替换为newStr
	 * @return
	 */
	public static boolean upFileContent(java.io.File file, String key,
			String newStr) {
		if (file == null || null == key || newStr == null) {
			return false;
		}
		try {
			String str = readFile(file);
			String targetStr = "";
			String[] strss = str.split("\n");
			for (String s : strss) {
				if (key.equals(s.split("=")[0])) {
					targetStr = s.split("=")[1].trim();
				}
			}
			// 替换
			String nstr = str.replaceAll(targetStr, newStr);
			writeFile(file, nstr);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
	/**
	 * 根据key 获得值 若对应的key 没有值则返回 null
	 * @param file
	 * @param keys
	 * @return
	 */
	public static String[] getValuesByKeys(java.io.File file,String[] keys){
		if (file == null || null == keys || keys.length == 0) {
			return null;
		}
		try {
			String str = readFile(file);
			String[] rs = new String[keys.length];
			String[] strss = str.split("\n");
				for(int i=0;i<keys.length;i++){
					for (String s : strss) {
						if (keys[i].equals(s.split("=")[0])) {
							if(s.split("=").length>1){
								rs[i] = (s.split("=")[1].trim());
							}else{
								rs[i] = "";
							}
							
						}
					}
				}
		
			return rs;
			} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		
		
	}
	/**
	 * 根据键获得值 若无 返回 空字符串
	 * @param file
	 * @param key
	 * @return
	 */
	public static String getValueByKey(java.io.File file,String key){
		if (file == null || null == key || key.length()==0) {
			return "";
		}
		String[] rs = getValuesByKeys(file ,new String[]{key});
		if(null!=rs&&rs.length!=0){
			return rs[0];
		}else{
			return "";
		}
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
//		FileUtil fu = new FileUtil();
//		boolean createmkdir = fu.createMkdir("D:/usr/local/centreon/filesGeneration/nagiosCFG/"+2);
//		if(createmkdir){
//			java.io.File file = FileUtil.createFile("D:/usr/local/centreon/filesGeneration/nagiosCFG/"+2+"/ssmtp.conf");
//			StringBuffer sb = new StringBuffer();
//			sb.append("hostname=ebondservice@126.com \n");
//			sb.append("AuthUser=ebondservice@126.com \n");
//			sb.append("AuthPass=djpf8888 \n");
//			sb.append("mailhub=smtp.126.com \n");
//			FileUtil.writeFile(file, sb.toString());//写入文件
//			
//			
////			FileUtil.writeFileAdd(file, "AuthUser=ebondservice@126.com \n");//写入文件
////			FileUtil.writeFileAdd(file, "AuthPass=djpf8888 \n");//写入文件
////			FileUtil.writeFileAdd(file, "mailhub=smtp.126.com \n");//写入文件
//			String str = fu.readFile(file);
//			String[] infos = str.split("\n");
//			for(String s:infos){
//				System.out.println(s);
//			}
			//System.out.println("=="+str);
//		}
		java.io.File file = FileUtil.createFile("D:/test.txt");
		FileUtil.writeFile(file, "aa=123 \nbb=345");
		
		String rs = getValueByKey(file,"aa"); 
		System.out.println("rs == "+rs);
		
		String[] rss = getValuesByKeys(file ,new String[]{"aa","bb","cc","aa"});
		for(String s:rss){
			System.out.println("rsss = "+s);
		}
		
	}

}
